/**
 * @author baz
 */
package cat.state {
import bot.BotStateList;
import bot.BotView;

import cat.*;

import flash.ui.Keyboard;

import lib.KeyboardManager;

public class CatStateReady implements ICatState {

    private static const HIJACK_RADIUS:int = 50;

    private var view:CatView;
    private var botList:Vector.<BotView>;

    public function CatStateReady(catModel:CatView) {
        view = catModel;
    }

    public function init(... params):void {
        botList = params[0];
    }

    public function frameHandler():void {
        view.jumping && KeyboardManager.$.isDown(Keyboard.LEFT) && view.moveLeft();
        view.jumping && KeyboardManager.$.isDown(Keyboard.RIGHT) && view.moveRight();
        KeyboardManager.$.isDown(Keyboard.SPACE) && view.jump();
        checkHijack();
    }

    public function cleanUp():void {
        botList = null;
    }

    /**
     * Проверить на захват планешки
     * @return
     */
    private function checkHijack():void {
        for each (var botModel:BotView in botList) {
            // Проверяем условие сближения
            if (Math.abs(view.x - botModel.x) <= HIJACK_RADIUS  &&  Math.abs(view.y - botModel.y) <= HIJACK_RADIUS) {
                // Переходим в состояние захвата
                botModel.setState(BotStateList.HIJACK);
                startFight();
                view.setState(CatStateList.HIJACK, botModel);
                break;
            }
        }
    }

    /**
     * Set fight state to all non hijacked bots
     */
    private function startFight():void {
        for each (var botModel:BotView in botList) {
            if (!botModel.inState(BotStateList.HIJACK)) {
                botModel.setState(BotStateList.FIGHT, view);
            }
        }
    }
}
}
